package com.wss.merchant.service;

import com.aliyun.oss.OSSClient;
import com.wss.merchant.domain.PicUploadResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.util.UUID;

@Service
public class OssService {
    //允许上传的文件格式
    private static final String[] IMAGE_TYPE = new String[] {".bmp",".jpg",".gpeg",".gif",".png"};
    @Autowired
    private OSSClient ossClient;
    //oss桶名称
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    //oss访问外网访问路径
    @Value("${aliyun.oss.urlPrefix}")
    private String UrlPrefix;

    public PicUploadResult putImg(MultipartFile multipartFile){
        PicUploadResult picUploadResult = new PicUploadResult();
        //判断是否是图片对象
        boolean isImg = false;
        for(String type : IMAGE_TYPE){
            if(StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(),type)){
                isImg = true;
                break;
            }
        }
        if(!isImg){
            picUploadResult.setStatus("error");
            return picUploadResult;
        }
        String fileName = multipartFile.getOriginalFilename();
        String imgName = uFileName(fileName);
        //oss上传
        try{

            ossClient.putObject(bucketName,imgName,
                    new ByteArrayInputStream(multipartFile.getBytes()));
        }catch(Exception e){
            e.printStackTrace();
            picUploadResult.setStatus("error");
            return picUploadResult;
        }
        picUploadResult.setStatus("done");
        picUploadResult.setName(UrlPrefix + imgName);
        return picUploadResult;
    }
    public String uFileName(String FileName){
        String uuid = UUID.randomUUID().toString();

        return "images/" + uuid + FileName;
    }

}
